﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Framework.Common.Cache;
using System.ComponentModel.Composition;

namespace Framework.Cache.MemoryCache
{
    /// <summary>
    /// cache in memory
    /// </summary>
    [Export(typeof(ICache))]
    public class InMemoryCache : ICache
    {
        #region private member
        System.Runtime.Caching.MemoryCache mc;
        #endregion

        #region constructor
        /// <summary>
        /// 
        /// </summary>
        public InMemoryCache()
        {
            mc = System.Runtime.Caching.MemoryCache.Default;
        }
        #endregion

        #region ICache

        public bool Add(string key, object value)
        {
            return mc.Add(key, value, new DateTimeOffset(DateTime.MaxValue));
        }

        public bool Add(string key, object value, DateTime expiredTime)
        {
            return mc.Add(key, value, new DateTimeOffset(expiredTime));
        }

        public bool Contains(string key)
        {
            return mc.Contains(key);
        }

        public int Count
        {
            get { return mc.Count(); }
        }

        public void Flush()
        {
            mc.Trim(100);
        }

        public object GetData(string key)
        {
            return mc.Get(key);
        }

        public T GetData<T>(string key)
        {
            object obj = GetData(key);
            if (obj != null)
            {
                return (T)obj;
            }
            return default(T);
        }

        public bool Remove(string key)
        {
            mc.Remove(key);
            return true;
        }
        #endregion
    }
}
